﻿using UnityEngine;
using System.Collections;
using DG.Tweening;
using Cinemachine;

public class FingerGuessGame : BaseToyBoxGame
{


    private const string ASSET_PATH = "game_toybox/GuessGameRoot";
    private const string SOUND_PATH = "game_toybox/game_toybox_sound/";


    private Transform lediFlyTrans;
    private Transform trainTrans;
    private Transform rewardTrans;
    public bool gameStart = false;
    public bool gameEnd = false;
    public int winCount = 10;


    public override void OnStart(System.Action<bool> callback)
    {
        base.OnStart(callback);
        gameStart = false;
        Debug.Log("--------------- FingerGuessGame OnStart!");
        ResetData();
        //401010313
        PlaySoundAnim("401010313", "all_talk_02", 0.5f, true, () =>
        //PlayLeDiVoiceAnimation("401010313",   () =>
        {
            CreateGameRoot();

            /*lediTransform.DORotate(new Vector3(0, 180, 0), 0.5f).OnComplete(() =>
            {
                PlayAnimator("walk_p", 0.1f, true);
                lediTransform.DOMove(new Vector3(0,-5.389f,-140f), 1.5f).OnComplete(() =>
                {
                    PlayAnimator("idell_p", 0.1f, true);
                    ledi_ccdc.enabled = true;
                    train_ccdc.enabled = true;
                    ledi_ccdc.m_Speed = 350;
                    train_ccdc.m_Speed = 250;
                    Agent.enabled = false;
                });
            });*/
            //PlayAnimator("walk_p", 0.1f, true);
            base.SetDestination(new Vector3(0, 0, -140f), () =>
            {
                Debug.Log(" SetDestination  ===  ");
                PlayAnimator("idell_p", 0.1f, true);
                ledi_ccdc.enabled = true;
                train_ccdc.enabled = true;
                ledi_ccdc.m_Speed = 350;
                train_ccdc.m_Speed = 250;
                //Agent.enabled = false;
            });


            //actor.handle.PlaySound()
            this.AddTimerEx(2f, () =>
        {
            if (gameEnd)
                return;
            lediTransform.DORotate(new Vector3(0, 0, 0), 0.5f).OnComplete(() =>
            {
                if (gameEnd)
                    return;
                //“一个代表你，一个代表我，看看我们谁能获得奖杯！”
                //PlaySoundAnim("401010314", "all_talk_02", 0.2f, true, (string names) =>
                PlayLeDiVoiceAnimation("401010314", "all_all_talk8_p_", () =>
                {
                    this.AddTimerEx(0.5f, () =>
                    {
                        if (gameEnd)
                            return;
                        //游戏开始
                        StartGame();
                    });
                });
            });
        });
            /*this.AddTimerEx(3f, () => {

                if (completeCallback != null)
                    completeCallback(true);

            });*/
        },false);
    }

    void StartGame()
    {
        //游戏开始！快选择你想出的手势吧！
        PlaySoundAnim("401010315", "all_talk_02", 0.5f, true, () =>
        {
            if (gameEnd)
                return;
            Debug.Log("   播放藏手指 === ");
            PlayAnimator("hide_hand_p", 0.2f, false);
            this.AddTimerEx(0.27f, () =>
            {
                if (gameEnd)
                    return;
                ledi_ccdc.enabled = false;
                train_ccdc.enabled = false;
                gameStart = true;
                GuessWindow.Instance.gamestart = true;
                Debug.Log("  StartGame gameStart  true === " + gameStart);
            });
        });
    }

    float interval = 10f;
    public float timeOpeCount = 0;
    public override void OnUpdate()
    {
        //Debug.Log("  gameStart   1111 === " + gameStart);
        base.OnUpdate();
        //Debug.Log(ledi_ccdc.m_Position + "   === ledi_ccdc.m_Position ");        
        if (ledi_ccdc != null && ledi_ccdc.m_Speed != 0)
        {
            if (Vector3.Distance(lastlediflyPos, lediFlyTrans.position) < 0.5f)
            {
                Debug.Log("1111111 ==== ");
                ledi_ccdc.m_Speed = 0;
                lediFlyTrans.localPosition = new Vector3(90f, -5.3f, -12.6f);
                isFlyAroundEnd = true;
            }

        }
        if (isFlyAroundEnd && !isRewardOnPos)
        {
            WindowManager.Instance.OpenWindow(WinNames.GuessPanel);
            GuessWindow.Instance.callback = OnUIClick;
            GuessWindow.Instance.backMain_Action = GameEnd;
            rewardTrans.DOLocalJump(reawrdJumpPos, 50f, 1, 0.8f).OnComplete(() =>
            {
                Debug.Log("2222222 ===== ");
            });
            isRewardOnPos = true;
        }
        if (gameStart && !gameEnd)
        {
            //如果超过10秒没有操作，乐迪说：“我们休息一下再玩吧！”并有动作，游戏结束，所有道具直接消失，展示所有隐藏的功能按钮
            timeOpeCount += Time.deltaTime;
            if (timeOpeCount >= interval)
            {                
                timeOpeCount = 0;
                PlaySoundAnim("401010326", "all_talk_02", 0.4f, true,()=> {
                    GameEnd();
                });
            }
        }
    }
    bool isRewardOnPos = false;
    bool isFlyAroundEnd = false;
    CinemachineDollyCart ledi_ccdc;
    CinemachineDollyCart train_ccdc;
    Vector3 lastlediflyPos;
    Vector3 reawrdJumpPos;
    Vector3 rewardMyWinPos;
    Transform lediRightHand;

    GameObject go;
    private void CreateGameRoot()
    {
        lastlediflyPos = new Vector3(89.6f, -4.8f, -6.5f);
        reawrdJumpPos = new Vector3(-110.8f, -5.9f, 11.7f);
        rewardMyWinPos = new Vector3(-4.4f, 32.1f, 114.6f);
        go = Res.LoadObj(ASSET_PATH);
        if (go != null)
        {
            go.transform.SetParent(toyboxGameRoot);
            lediFlyTrans = go.transform.Find("lediFly_obj");
            ledi_ccdc = lediFlyTrans.GetComponent<CinemachineDollyCart>();
            ledi_ccdc.m_Speed = 0;
            trainTrans = go.transform.Find("train _obj");
            train_ccdc = trainTrans.GetComponent<CinemachineDollyCart>();
            train_ccdc.m_Speed = 0;
            rewardTrans = go.transform.Find("reward_obj");

            lediRightHand = lediTransform.Find("101001000@skin/root/bip001/bip0032/Bip001 Spine/bip0029/bip0018/bip0017/bip0016/bip0015/bonebody34/right_hand");
            Debug.Log(lediRightHand.name.ToString() + " ===  lediRightHand  ");
        }
        //train _obj   90  -6.4   50   ledifly  90 -5.3  -12.6      reward -204.5  79.2  11.7 
    }
    /// <summary>
    /// 当前乐迪出的类型
    /// </summary>
    public FingerGuessType curLediGuessType;
    /// <summary>
    /// 当前火车玩家出的类型
    /// </summary>
    public FingerGuessType curTrainGuessType;
    public void OnUIClick(FingerGuessType type)
    {
        timeOpeCount = 0;
        Debug.Log(type + "   ==== type  , gameStart == " + gameStart);
        if (!gameStart)
        {
            Debug.Log("  ================ ");
            return;
        }
        if (gameEnd)
        {
            //Debug.Log("休息一下 ========= ");
            //PlaySoundAnim("401010326", "all_talk_02", 0.2f, true);
            return;
        }

        gameStart = false;
        

        curLediGuessType = (FingerGuessType)Random.Range(1, 4);
        Debug.Log("curLediGuessType === " + curLediGuessType);
        curTrainGuessType = type;
        //乐迪出拳
        var length = AudioManager.Instance.PlaySound(SOUND_PATH + "401010316").Length;
        this.AddTimerEx(length, () =>
        {
            if (gameEnd)
                return;
            this.AddTimerEx(0.1f, () =>
            {
                if (gameEnd)
                    return;
                string actName = "";
                PlaySoundAnim(GetVoidType(curLediGuessType, ref actName), actName, 0.1f, false, () =>
                 {
                     if (gameEnd)
                         return;
                     this.AddTimerEx(0.4f, () =>
                     {
                         if (gameEnd)
                             return;
                         //判断胜利
                         int winType = CalWin();
                         Debug.Log("  winType ====  " + winType);
                         string sound = "";
                         string act = "";
                         if (winType == 0)
                         {
                             //平手  401010322
                             sound = "401010322";
                             act = "all_happy_0";
                         }
                         else if (winType == 1)
                         {
                             //胜利   401010320
                             myWinCount++;
                             sound = "401010320";
                             act = "good_p";
                             trainTrans.DOLocalMoveX(trainTrans.localPosition.x - 10, 0.4f).SetEase(Ease.Linear);
                             AudioManager.Instance.PlaySound("game_toybox/game_toybox_sound/601010209");
                         }
                         else if (winType == 2)
                         {
                             //输   401010321
                             lediWinCount++;
                             sound = "401010321";
                             act = "all_unknow_0";
                             lediFlyTrans.DOLocalMoveX(lediFlyTrans.localPosition.x - 10, 0.4f).SetEase(Ease.Linear);
                             AudioManager.Instance.PlaySound("game_toybox/game_toybox_sound/601010208");
                         }
                         if (myWinCount == winCount || lediWinCount == winCount)
                         {
                             gameEnd = true;
                             GameWin();
                             return;
                         }
                         System.Action action = () =>
                     {
                         this.AddTimerEx(0.5f, () =>
                         {
                                 //我们继续吧
                                 PlayLeDiVoiceAnimation("401010323", "all_all_talk8_p_", () =>
                                 
                         //PlaySoundAnim("401010323", "all_talk_02", 0, true, (string names4) =>
                         {
                             GuessWindow.Instance._bu_btn.GetComponent<Transform>().GetChild(0).SetActive(false);
                             GuessWindow.Instance._jd_btn.GetComponent<Transform>().GetChild(0).SetActive(false);
                             GuessWindow.Instance._st_btn.GetComponent<Transform>().GetChild(0).SetActive(false);
                             PlayAnimator("hide_hand_p", 0, false);
                                 this.AddTimerEx(0.27f, () =>
                                 {
                                     gameStart = true;
                                     GuessWindow.Instance.gamestart = true;
                                 });
                             });
                         });
                     };
                         if (winType == 1)
                             PlaySoundAnim(sound, act, 0.5f, true, action, false);
                         else
                             PlayLeDiVoiceAnimation(sound, act, action);
                     });

                 }, false);
            });
        });
    }

    void GameWin()
    {
        Debug.Log("开始颁奖 ========= ");
        if (myWinCount == winCount)
        {
            //我赢取十次比赛的胜利
            PlayLeDiVoiceAnimation("401010324", "all_happy_0", () =>
            {
                //乐迪说：“你真棒！奖杯是属于你的！”并有称赞动作，然后奖杯飞到屏幕正中间，同时有烟花特效，持续3秒后所有道具全部消失
                Debug.Log("奖杯飞到屏幕正中间，同时有烟花特效，持续3秒后所有道具全部消失");

            });
            rewardTrans.DOLocalJump(rewardMyWinPos, 50f, 1, 1.5f).OnComplete(() =>
            {
                rewardTrans.GetChild(0).SetActive(true);
                Debug.Log("  rewardTrans.DOLocalJump ===== ");
            });
            //播放烟花效果
           
        }
        else
        {
            //乐迪赢   
            Vector3 rePos = lediRightHand.TransformPoint(new Vector3(0, 0, 0));
            rewardTrans.DOLocalJump(rePos, 50f, 1, 1f).OnComplete(() =>
            {
                rewardTrans.SetParent(lediRightHand);
                rewardTrans.localPosition = new Vector3(0, 0, 0);
                PlayLeDiVoiceAnimation("401010325", "hold_trophy_p_", () =>
                {
                        //乐迪胜利，奖杯飞到乐迪手里，乐迪举起奖杯说：“Yahoo！我赢得了奖杯！”同时有烟花特效，持续3秒后所有道具全部消失
                        Debug.Log("乐迪胜利，奖杯飞到乐迪手里，乐迪举起奖杯说：“Yahoo！我赢得了奖杯！”同时有烟花特效，持续3秒后所有道具全部消失");
                });

                //播放烟花效果
                
            });

        }

        //游戏结束
        this.AddTimerEx(6f, () => {
            GameEnd();
        });

    }
    /// <summary>
    /// 游戏结束
    /// </summary>
    public void GameEnd()
    {
        animator.CrossFade("idell_p", 0.2f);
        AudioManager.Instance.StopAllSound();
        timeOpeCount = 0;
        gameEnd = true;
        Debug.Log("GameEnd  === ");
        base.Agent.enabled = true;
        if (go != null)
        {
            Debug.Log(" OnExit ");
            GameObject.Destroy(rewardTrans.gameObject);
            GameObject.Destroy(go);
            go = null;
        }
        WindowManager.Instance.CloseWindow(WinNames.GuessPanel);
        OnGameComplete(true);
    }
    public override void OnExit()
    {
        base.OnExit();       
    }

    public void ResetData()
    {
        timeOpeCount = 0; 
        lediWinCount = 0;
        myWinCount = 0;

        gameStart = false;
        GuessWindow.Instance.gamestart = false;
        gameEnd = false;

        isRewardOnPos = false;
        isFlyAroundEnd = false;

        /*trainTrans.localPosition = new Vector3(90f, -6.4f, 50f);
        lediFlyTrans.localPosition = new Vector3(90f, -5.3f, -12.6f);
        rewardTrans.localPosition = new Vector3(-204.5f, 79.2f, 11.7f);*/
    }
    /// <summary>
    /// 胜利十次
    /// </summary>
    public int lediWinCount = 0;
    public int myWinCount = 0;
    int CalWin()
    {
        //1 表示玩家 火车赢  2 表示玩家输乐迪赢  0 表示平手
        int winType = 0;
        if (curLediGuessType == FingerGuessType.St)
        {
            switch (curTrainGuessType)
            {
                case FingerGuessType.St:
                    winType = 0;
                    break;
                case FingerGuessType.Jd:
                    winType = 2;
                    break;
                case FingerGuessType.Bu:
                    winType = 1;
                    break;
            }
        }
        else if (curLediGuessType == FingerGuessType.Jd)
        {
            switch (curTrainGuessType)
            {
                case FingerGuessType.St:
                    winType = 1;
                    break;
                case FingerGuessType.Jd:
                    winType = 0;
                    break;
                case FingerGuessType.Bu:
                    winType = 2;
                    break;
            }
        }
        else if (curLediGuessType == FingerGuessType.Bu)
        {
            switch (curTrainGuessType)
            {
                case FingerGuessType.St:
                    winType = 2;
                    break;
                case FingerGuessType.Jd:
                    winType = 1;
                    break;
                case FingerGuessType.Bu:
                    winType = 0;
                    break;
            }
        }
        return winType;
    }

    string GetVoidType(FingerGuessType type, ref string actName)
    {
        string sound = "";
        switch (type)
        {
            case FingerGuessType.St:
                sound = "401010317";
                actName = "caiquan_shi";
                break;
            case FingerGuessType.Jd:
                sound = "401010318";
                actName = "caiquan_jian";
                break;
            case FingerGuessType.Bu:
                sound = "401010319";
                actName = "caiquan_bu";
                break;
        }
        return sound;
    }
    private void PlaySoundAnim(string voicePath, string animName, float fade, bool isLoop, System.Action callback = null, bool isChangeIdel = true)
    {
        AudioClip clip = AudioManager.Instance.GetAudioClip(SOUND_PATH + voicePath);
        if (AudioManager.Instance.IsPlayingSoundClip(clip)) return;
        var length = AudioManager.Instance.PlaySound(SOUND_PATH + voicePath).Length;
        PlayAnimator(animName, fade, isLoop);
        this.AddTimerEx(length, () =>
        {
            if (gameEnd)
                return;
            if (isChangeIdel)
            {
                PlayAnimator("idell_p", fade, true);
                Debug.Log("  PlaySoundAnim  idell_p ");
            }
            if (callback != null)
                callback();
        });
    }

    private bool isPlayingLdAniSound = false;
    public void PlayLeDiVoiceAnimation(string voicePath, string actName, System.Action act = null)
    {
        AudioClip clip = AudioManager.Instance.GetAudioClip(SOUND_PATH + voicePath);
        if (isPlayingLdAniSound)
        {
            return;
        }
        isPlayingLdAniSound = true;
        PlayAnimator(actName + "1", 0.2f, false);
        this.AddTimerEx(0.5f, () =>
        {
            if (gameEnd)
                return;
            var length = AudioManager.Instance.PlaySound(SOUND_PATH + voicePath).Length;
            PlayAnimator(actName + "2", 0f, true);
            this.AddTimerEx(length, () =>
            {
                if (gameEnd)
                    return;
                PlayAnimator(actName + "3", 0f, false);
                if (act != null)
                    act();

                isPlayingLdAniSound = false;
            });
        });
    }



}
